package com.labot.webapp.action;

import java.util.HashMap;
import java.util.List;

import org.springframework.security.core.context.SecurityContextHolder;

import com.labot.dao.SearchException;
import com.labot.model.Config;
import com.labot.model.User;
import com.labot.types.AuditType;
import com.labot.types.ConstantsGrupsType;
import com.labot.types.ConstantsType;
import com.labot.util.StackTraceUtils;
import com.labot.webapp.action.messages.TextMessagesType;
import com.labot.webapp.listener.StartupListener;
import com.labot.webapp.util.RequestUtil;

/**
 * Action for facilitating User Management feature.
 */
public class ConfigAction extends BaseAction {
    private static final long serialVersionUID = 6776548938712115191L;
    private HashMap<ConstantsGrupsType, List<Config>> configs = new HashMap<ConstantsGrupsType, List<Config>>();
    private HashMap<String, String> valoresCargados;
    private String mail;

    /**
     * Default: just returns "success"
     *
     * @return "success"
     */
    public String execute() {
    	try {    		
    		User user = userManager.getUserByUsername( SecurityContextHolder.getContext().getAuthentication().getName().toString() );
    		mail = user.getEmail();
    	} catch (Exception e) {
    		// no se pudo obtener el mail
    	}
        return SUCCESS;
    }
    
    public String cancel() {
    	return CANCEL;
    }

    public String saveAll() {
    	List<Config> configs = null;
    	try {
    		configs = configManager.getAllConfigs();
        } catch (SearchException se) {
            addActionError(se.getMessage());
        }
    	if (configs == null) {
    		addActionError(super.getText(TextMessagesType.CONFIGACTION_ERROR_DATA.getKey()));//"ERROR al obtener datos de configuraci&oacute;n");
    		return SUCCESS;
    	}
    	String mensaje = super.getText(TextMessagesType.CONFIGACTION_SAVE_TITLE.getKey()); //"Se han modificado las siguientes Constantes: ";
    	Boolean modificaciones = false;
    	for (Config config : configs) {
			try {
				ConstantsType constant = config.getConstant();
				String newValue = valoresCargados.get(constant.toString());
				String oldValue = config.getValue();
				if (!(newValue.equals(oldValue))) { 
					if (!newValue.equals(Config.OBSCURED_PASSWORD)) {
						configManager.modifyConfig(config.getId(), newValue);
						log.info("Se ha modificado la Config: " + config.getConstant() + " - valor viejo: " + oldValue + " - valor nuevo: " + newValue);
						mensaje = mensaje.concat(config.getConstant() + ", ");
						modificaciones = true;
						super.log(AuditType.INFO, "" + config.getConstant() + " changed. Old: " + oldValue + " - New: " + newValue);
					}
				}
				
			} catch (Exception e) {
				saveErrorMessage(super.getText(TextMessagesType.CONFIGACTION_ERROR_SAVE.getKey()) + " " + config.getConstant()); //"ERROR al grabar Constante: " + config.getConstant());
			}
		}
    	if (modificaciones) {    	
    		mensaje = mensaje.substring(0, mensaje.length()-2);
    		saveMessage(mensaje);
    		try {    		
    			StartupListener.loadConfig(getSession().getServletContext());
    			super.mailEngine.setFrom(StartupListener.getConfigValue(ConstantsType.MAIL_DEFAULT_FROM));
    		} catch (Exception e) {
    			String error = super.getText(TextMessagesType.CONFIGACTION_RELOAD.getKey()); //"ERROR al recargar las Configs en el Sistema, reinicie la aplicaci&oacte;n para reflejar los cambios.";
    			saveErrorMessage(error);
    			log.error(error);
    		}
    	} else {
    		saveMessage(super.getText(TextMessagesType.CONFIGACTION_NO_MODIFICATIONS.getKey()));
    	}
    	
    	
    	return SUCCESS;
    }
    
    public String sendTestMail() {
    	try {    		
    		mailMessage.setTo(mail);
    		mailMessage.setFrom(StartupListener.getConfigValue(ConstantsType.MAIL_DEFAULT_FROM));
    		mailMessage.setSubject(getText(TextMessagesType.TEST_MAIL_SUBJECT.getKey()));
    		mailMessage.setText(getText(TextMessagesType.TEST_MAIL_BODY.getKey()));
    		super.mailEngine.send(mailMessage);
    		saveMessage(super.getText(TextMessagesType.CONFIGACTION_CHECKMAIL_SENT.getKey()) + " " + mail);
    	} catch (Exception e) {
    		String stack = StackTraceUtils.getStackTrace(e);
    		if(stack.length()>100) {
    			stack = stack.substring(0, 1000);
    		}
    		saveErrorMessage(super.getText(TextMessagesType.CONFIGACTION_TEST_MAIL_ERROR.getKey()));
    		saveExceptionMessage( stack + "...");
    	}
    	return SUCCESS;
    }


    /**
     * Fetch all Configs from database and put into local "configs" variable for retrieval in the UI.
     *
     * @return "success" if no exceptions thrown
     */
    public String list() {
        try {
        	for (ConstantsGrupsType group : ConstantsGrupsType.values()) {				
        		configs.put(group, configManager.getConfigs(group));
			}
        } catch (SearchException se) {
            addActionError(se.getMessage());
        }
        return SUCCESS;
    }

	public HashMap<ConstantsGrupsType, List<Config>> getConfigs() {
		return configs;
	}

	public HashMap<String, String> getValoresCargados() {
		return valoresCargados;
	}

	public void setValoresCargados(HashMap<String, String> valoresCargados) {
		this.valoresCargados = valoresCargados;
	}

	public String getMail() {
		return mail;
	}

	public void setMail(String mail) {
		this.mail = mail;
	}
    

}
